package com.yzh.common.manager;

import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class RedisLimiterManager {
    @Resource
    private RedissonClient redissonClient;
    public void doRateLimit(String key) {
        //创建名为key的限流器， 每秒最多访问两次
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        rateLimiter.trySetRate(RateType.OVERALL, 2, 1, RateIntervalUnit.SECONDS);

        //每当一个操作来了后，取一个令牌
        boolean result = rateLimiter.tryAcquire(1);
        if (!result) throw new RuntimeException("请求过于频繁！");
    }
}
